% This m-scripts checks claims about the rank of coefficient matrices in a single
% environment (i.e., when S=1 in LQT2019) under exclusion restrictions 
% Date: Nov 13, 2018
clear; clc;

%% define linear system and solve for (a_k,b_k) for k<K
K = 8; % # of regressors
gamma = [zeros(1,1); rand(K-1,1)]; % draw parameter value of contextual effeccts 
lam   = rand(1,1); % draw parameter value for peer effects
beta  = [1; 0; rand(K-2,1)];  % direct effects do not vary with group size
% Restrictions imposed:
% - 1st regressor has no contextual effect
% - 2nd regressor has no individual effect    
abMat = zeros(2,K-1); % matrix that keeps track of (a_k,b_k) for k < K
% Dimensions of 'abMat'
% - 1st dim: (a,b) 
% - 2nd dim: index for regressors (k) 
M = zeros(K,1);
% Dimensions of 'M'
% - 1st dim: index for regressors (k) 
% - 2nd dim: class size, L or H
for k = 1:K-1,
        abMat(:,k) = [beta(k) beta(K); gamma(k) gamma(K)]\[1;-lam];
        M(k) = (beta(k)+gamma(k))/(1-lam);
    end;
M(K) = (beta(K)+gamma(K))/(1-lam);
a = abMat(1,:)'; % 'a' is (K-1)-by-1
b = abMat(2,:)'; 

%% construct the coefficient matrix and the vector of constants in the linear system
pi = zeros(2*(K-1)+K,2*K+1);  d = zeros(2*(K-1)+K,1);
% first column in pi
v = zeros(2*(K-1)+K,1); 
v(2*(K-1)+1:end) = M; 
v(K:2*(K-1)) = ones(K-1,1);
pi(:,1) = v;
% column 2 to K+1 in pi
mat1 = zeros(2*(K-1)+K,K); 
mat1(1:K-1,:) = [diag(a) b];
mat1(2*(K-1)+1:end ,:) = eye(K);  
pi(:,2:K+1) = mat1;
% last k columnis in pi
mat2 = zeros(2*(K-1)+K,K); 
mat2(K:2*(K-1),:) = [diag(a) b];    
mat2( 2*(K-1)+1:end ,:) = eye(K);    
pi(:,K+2:end) = mat2;
d(:) = [ones(K-1,1); zeros(K-1,1); M];

%% check the system holds
disp('coef matrix without E.R.:');
disp('(# rows ; # columns ; # ranks)');
disp([size(pi), rank(pi)]); 
theta = [lam; beta; gamma];
max(abs(pi*theta - d)); % null(Phi),

%% add exclusion restrictions and check rank conditions

% disp('*************************************');
% disp('coef. matrix with E.R.: first two regressors have no contextual effects');
% R = [zeros(1,K+1), 1, zeros(1,K-1); ... % 1st regresssor has no contextual effect
%      zeros(1,K+1), 0, 1, zeros(1,K-2)]; % 2nd regressor has no contextual effect
% C = zeros(2,1);
% disp('(# rows ; # columns ; # ranks)');
% disp([size([pi;R]), rank([pi;R])]);
% max(abs([pi;R]*theta - [d;C]));

disp('*************************************');
disp('coef. matrix with E.R.: 1st regssor has no contextual effect; 2nd has no individual effect');
R = [zeros(1,K+1), 1, zeros(1,K-1); ... % 1st regresssor has no contextual effect
     0 0 1 zeros(1,K-2), zeros(1,K)]; % 2nd regressor has no individual effect
C = zeros(2,1);
disp('(# rows ; # columns ; # ranks)');
disp([size([pi;R]), rank([pi;R])]);
max(abs([pi;R]*theta - [d;C]));

